/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef, useCallback, useEffect } from "react";
import { message, Modal, Row, Col, Icon, Table } from "antd";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import update from "immutability-helper";
import { setLStorage, getLStorage } from "@/utils/utils";
import { cloneDeep } from "lodash";
import "./ColumnsSetting.less";

const TYPE = "DraggableBodyRow";

const DraggableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
  const ref = useRef();
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: TYPE,
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? " drop-over-downward" : " drop-over-upward",
      };
    },
    drop: item => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type: TYPE,
    item: { index },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ""}`}
      style={{ cursor: "move", ...style }}
      {...restProps}
    />
  );
};

const components = {
  body: {
    row: DraggableBodyRow,
  },
};

const initColumns = [
  {
    title: "订单信息",
    key: "order_info",
    selected: true,
  },
  {
    title: "快递品牌",
    key: "brand",
    selected: true,
  },
  {
    title: "寄件信息",
    key: "sendInfo",
    selected: true,
  },
  {
    title: "收件信息",
    key: "getInfo",
    selected: true,
  },
  {
    title: "处理方",
    key: "courierInfo",
    selected: true,
  },
  {
    title: "时间节点",
    key: "update_at",
    selected: true,
  },
  {
    title: "物品类型",
    key: "package_info",
    selected: true,
  },
  {
    title: "备注",
    key: "package_note",
    selected: true,
  },
  {
    title: "订单状态",
    key: "statusText",
    selected: true,
  },
  {
    title: "运单号",
    key: "waybill_no",
    selected: true,
  },
  {
    title: "优惠信息",
    key: "iscountAmount",
    selected: true,
  },
  {
    title: "结算重量",
    key: "charging_weight",
    selected: true,
  },
  {
    title: "支付信息",
    key: "payInfo",
    selected: true,
  },
];

const ColumnsSetting = ({ visible, handleVisible, setColumns, shop_id }) => {
  const [tableData, setTableData] = useState(initColumns);
  const [selectedRowKeys, setSelectedRowKeys] = useState(
    initColumns.filter(i => i.selected).map(i => i.key)
  );

  const handleColumns = useCallback(
    () => {
      setLStorage(`${shop_id}orderDetailColumns`, tableData);
      setColumns && setColumns();
      handleVisible(false);
      message.success("设置成功！");
    },
    [setColumns, tableData, handleVisible, shop_id]
  );

  const handleSelectRows = (selected = []) => {
    tableData.forEach(val => {
      if (selected.includes(val.key)) {
        val.selected = true;
      } else {
        val.selected = false;
      }
    });
    setTableData(tableData);
    setSelectedRowKeys(selected);
  };

  const moveRow = useCallback(
    (dragIndex, hoverIndex) => {
      // 防止引用，导致提交时，数据不更新
      const clonedData = cloneDeep(tableData);
      const dragRow = clonedData[dragIndex];

      setTableData(
        update(clonedData, {
          $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
        })
      );
    },
    [tableData]
  );

  useEffect(
    () => {
      if (visible) {
        // 获取本地设置，更新数据
        const localData = getLStorage(`${shop_id}orderDetailColumns`) || initColumns;
        setTableData(localData);
        setSelectedRowKeys(localData.filter(i => i.selected).map(i => i.key));
      }
    },
    [visible, shop_id]
  );

  return (
    <Modal
      destroyOnClose
      title="通过勾选展示/关闭对应数据项，通过拖拽调整表格数据展示顺序"
      onOk={handleColumns}
      onCancel={() => handleVisible(false)}
      visible={visible}
    >
      <DndProvider backend={HTML5Backend}>
        <Table
          dataSource={tableData}
          rowSelection={{
            selectedRowKeys,
            onChange: handleSelectRows,
          }}
          columns={[
            {
              title: "",
              dataIndex: "title",
              key: "key",
              render: title => (
                <Row type="flex" justify="space-between">
                  <Col>{title}</Col>
                  <Col>
                    <Icon type="menu" />
                  </Col>
                </Row>
              ),
            },
          ]}
          rowKey="key"
          pagination={false}
          components={components}
          onRow={(_, index) => ({
            index,
            moveRow,
          })}
        />
      </DndProvider>
    </Modal>
  );
};

export default ColumnsSetting;
